export SHELL = /bin/sh

export ROOT = $(shell pwd)/
export CC = gcc
export ARCH = $(shell arch)

export INCLUDE = $(ROOT)include/
export LIB = $(ROOT)lib/
export SRC = $(ROOT)src/
export CONF = $(ROOT)conf/

export INOTIFY_SRC = $(SRC)inotify/
export CONFIG_SRC = $(SRC)config/
export UTILITY_SRC = $(SRC)utility/

#paras when release
TARGET = $(ROOT)bin/inotify-sync
#paras when debug
DEBUG_TARGET = $(ROOT)bin/debug-inotify-sync
export DEBUG_FLAGS = -g -Wall

#All
.PHONY: all
all: $(TARGET)
$(TARGET): main.o inotify config
	$(CC) -o $(TARGET) -I$(INOTIFY_SRC) -I$(CONFIG_SRC) -I$(UTILITY_SRC) main.o -L$(LIB) -linotify -lconfig -lpthread
main.o: $(SRC)main.c
	$(CC) -c -I$(INOTIFY_SRC) -I$(CONFIG_SRC) -I$(UTILITY_SRC) -I$(INCLUDE) $(SRC)main.c
inotify: $(INOTIFY_SRC)event_watcher.c $(INOTIFY_SRC)event_watcher.h $(INOTIFY_SRC)event_handler.c $(INOTIFY_SRC)event_handler.h
	cd $(INOTIFY_SRC) && make all
config: $(CONFIG_SRC)profile.c $(CONFIG_SRC)profile.h $(CONFIG_SRC)profile_parser.c $(CONFIG_SRC)profile_parser.h
	cd $(CONFIG_SRC) && make all

#Debug
.PHONY: debug
debug: $(DEBUG_TARGET)
$(DEBUG_TARGET): debug_main.o debug_inotify debug_config
	$(CC) $(DEBUG_FLAGS) -o $(DEBUG_TARGET) -I$(INOTIFY_SRC) -I$(CONFIG_SRC) -I$(UTILITY_SRC) debug_main.o -L$(LIB) -ldebug_inotify -ldebug_config -lpthread
debug_main.o: $(SRC)main.c
	$(CC) -c $(DEBUG_FLAGS) -o debug_main.o -I$(INOTIFY_SRC) -I$(CONFIG_SRC) -I$(UTILITY_SRC) -I$(INCLUDE) $(SRC)main.c
debug_inotify: $(INOTIFY_SRC)event_watcher.c $(INOTIFY_SRC)event_watcher.h $(INOTIFY_SRC)event_handler.c $(INOTIFY_SRC)event_handler.h
	cd $(INOTIFY_SRC) && make debug
debug_config: $(CONFIG_SRC)profile_parser.c $(CONFIG_SRC)profile_parser.h $(CONFIG_SRC)profile.c $(CONFIG_SRC)profile.h
	cd $(CONFIG_SRC) && make debug

#Clean
.PHONY: clean
clean:
	-rm *.o $(TARGET) $(DEBUG_TARGET)
	-cd $(INOTIFY_SRC) && make clean
	-cd $(CONFIG_SRC) && make clean

#Install
.PHONY: install
install:
	@if [ "$(USER)" != "root" ];\
	then \
		echo "Please run 'make install' as root!";\
		exit 1;\
	fi
	@if [ -e /usr/local/etc/inotify-sync ];\
	then \
		rm -rf /usr/local/etc/inotify-sync;\
	fi
	@cp -R $(CONF) /usr/local/etc/inotify-sync
	@if [ -e /usr/local/bin/inotify-sync ];\
	then \
		rm -rf /usr/local/bin/inotify-sync;\
	fi
	@cp $(TARGET) /usr/local/bin/inotify-sync
	@if [ -e /var/log/inotify-sync ];\
	then \
		rm -rf /var/log/inotify-sync;\
	fi
	@mkdir /var/log/inotify-sync

#Uninstall
.PHONY: uninstall
uninstall:
	@if [ "$(USER)" != "root" ];\
	then \
		echo "Please run 'make uninstall' as root!";\
		exit 1;\
	fi
	@if [ -e /usr/local/etc/inotify-sync ];\
	then \
		rm -rf /usr/local/etc/inotify-sync;\
	fi
	@if [ -e /usr/local/bin/inotify-sync ];\
	then \
		rm -rf /usr/local/bin/inotify-sync;\
	fi
	@if [ -e /var/log/inotify-sync ];\
	then \
		rm -rf /var/log/inotify-sync;\
	fi
